<script lang="ts" setup>
import {ref, onUnmounted, onMounted} from 'vue';
import WebSocketService from '@/webSocket/WebSocketService.js';
import {adminTokenStore} from '@/stores/adminToken'
import {ElMessage, ElNotification} from "element-plus";
import {getBorroweuests, upBorroweuestsStatus} from "@/api/admin"
import { Warning } from '@element-plus/icons-vue'

const adminToken = adminTokenStore()

const sid = "admin-" + adminToken.token

const messages = ref<string[]>([]); // 存储接收到的消息
const wsService = new WebSocketService('/ws/' + sid);

// 连接 WebSocket
wsService.connect();

//收到消息
wsService.ws.onmessage = (event) => {
  try {
    const data = JSON.parse(event.data)
    
    if (data.type === 'BORROW_REQUEST') {
      // 处理借阅请求相关的消息
      switch (data.action) {
        case 'refresh':
          // 刷新数据
          getBorroweuestsList()
          
          // 根据消息类型显示不同的提示
          if (data.message.includes('新的借阅申请')) {
            ElNotification({
              title: '新的借阅申请',
              message: '有新的借阅申请待处理',
              type: 'info',
              position: 'top-right'
            })
          } else if (data.message.includes('借阅申请已取消')) {
            ElNotification({
              title: '借阅申请取消',
              message: `用户 ${data.data.userName} 取消了《${data.data.bookTitle}》的借阅申请`,
              type: 'warning',
              position: 'top-right'
            })
          }
          break
          
        default:
          console.warn('未知的 action:', data.action)
      }
    }
  } catch (error) {
    console.error('处理 WebSocket 消息时出错:', error)
  }
}

// 组件卸载时清理资源
onUnmounted(() => {
  wsService.close();
});

//页面功能
const tableData = ref([])

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(10)
const username = ref('')
const status = ref('')

//请求的json数据
const getBorroweuestsDTO = ref({
  "pageNumber": "",
  "pageSize": "",
  "username": "",
  "status": ""
})

//调用方法获取图书借阅申请信息
const getBorroweuestsList = async () => {
  getBorroweuestsDTO.value.pageNumber = currentPage4.value
  getBorroweuestsDTO.value.pageSize = pageSize4.value
  const response = await getBorroweuests(getBorroweuestsDTO.value);
  tableData.value = response.data.results;
  total.value = response.data.total;
}

onMounted(() => {
  getBorroweuestsList()
})

// 每页条数发变化
const handleSizeChange = (val: number) => {
  currentPage4.value = val
  console.log(`${val} items per page`)
  getBorroweuestsList()
}

// 当前页码发生变化
const handleCurrentChange = (val: number) => {
  pageSize4.value = val
  console.log(`current page: ${val}`)
  getBorroweuestsList()
}

//状态选择器
const options = [
  {
    value: '待审核',
    label: '待审核',
  },{
    value: '已通过',
    label: '已通过',
  },{
    value: '已拒绝',
    label: '已拒绝',
  }
]

// 提交搜索
const onSubmit = () => {
  getBorroweuestsDTO.value.username = username.value
  getBorroweuestsDTO.value.status = status.value
  getBorroweuestsList()
}

// 清空输入框
const onSubmitEmpty = () => {
  getBorroweuestsDTO.value.username = ''
  getBorroweuestsDTO.value.status = ''
  username.value = ''
  status.value = ''
  getBorroweuestsList()
}

// 添加弹窗相关的响应式变量
const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const rejectRow = ref(null)

// 修改拒绝按钮的处理方法
const reject = (row) => {
  rejectDialogVisible.value = true
  rejectRow.value = row
}

// 添加确认拒绝的方法
const confirmReject = async () => {
  if (!rejectReason.value) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  try {
    const rejectData = {
      requestId: rejectRow.value.requestId,
      status: '已拒绝',
      reviewDate: new Date(),
      comments: rejectReason.value
    }
    
    await upBorroweuestsStatus(rejectData)
    ElMessage.success('已拒绝申请')
    rejectDialogVisible.value = false
    rejectReason.value = ''
    await getBorroweuestsList() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 添加状态标类型判断方法
const getStatusType = (status: string) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '待审核':
      return 'warning'
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

// 添加同意弹窗相关的响应式变量
const approveDialogVisible = ref(false)
const approveRow = ref(null)

// 修改同意按钮的处理方法
const throughThe = (row) => {
  approveDialogVisible.value = true
  approveRow.value = row
}

// 添加确认同意的方法
const confirmApprove = async () => {
  try {
    const approveData = {
      requestId: approveRow.value.requestId,
      status: '已通过',
      reviewDate: new Date(),
      comments: '同意借阅申请'
    }
    
    await upBorroweuestsStatus(approveData)
    ElMessage.success('已同意申请')
    approveDialogVisible.value = false
    await getBorroweuestsList() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

</script>

<template>

  <!-- 图书借阅申请列表 -->
  <el-card>
    <div class="card-header">
      <span>借阅申请</span>
    </div>
    <el-divider/>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="username" style="width: 240px" placeholder="请输入完整的用户名"/>
      </el-form-item>
      <el-form-item>
        <el-select
            v-model="status"
            clearable
            placeholder="请选择申请状态"
            style="width: 240px"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitEmpty">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="requestId" label="序号"/>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="title" label="书名"/>
      <el-table-column prop="requestDate" label="申请时间"/>
      <el-table-column prop="status" label="申请状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="操作" width="180">
        <template #default="{row}">
          <div>
            <el-button type="primary" plain @click.stop="throughThe(row)">同意</el-button>
            <el-button type="danger" plain @click.stop="reject(row)">拒绝</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
          class="el-p"
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 15, 20, 25]"
          layout="jumper, total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 拒绝原因弹窗 -->
  <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝借阅申请"
      width="40%"
  >
    <el-descriptions :column="1" border size="large" class="reject-info">
      <el-descriptions-item label="申请用户">
        {{ rejectRow?.username }}
      </el-descriptions-item>
      <el-descriptions-item label="申请书籍">
        {{ rejectRow?.title }}
      </el-descriptions-item>
      <el-descriptions-item label="申请时间">
        {{ rejectRow?.requestDate }}
      </el-descriptions-item>
    </el-descriptions>

    <el-divider content-position="left">拒绝原因</el-divider>
    
    <el-form>
      <el-form-item>
        <el-input
            v-model="rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
            resize="none"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">
          确认拒绝
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 同意申请弹窗 -->
  <el-dialog
      v-model="approveDialogVisible"
      title="同意借阅申请"
      width="40%"
  >
    <el-descriptions :column="1" border size="large" class="approve-info">
      <el-descriptions-item label="申请用户">
        {{ approveRow?.username }}
      </el-descriptions-item>
      <el-descriptions-item label="申请书籍">
        {{ approveRow?.title }}
      </el-descriptions-item>
      <el-descriptions-item label="申请时间">
        {{ approveRow?.requestDate }}
      </el-descriptions-item>
    </el-descriptions>

    <div class="warning-text">
      <el-icon><Warning /></el-icon>
      <span>同意后将为该用户分配此书的借阅权限，确认同意吗？</span>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove">
          确认同意
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>

.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
}

.reject-info {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: flex-end;
}

.approve-info {
  margin-bottom: 20px;
}

.warning-text {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #e6a23c;
  margin-top: 20px;
}

.warning-text .el-icon {
  font-size: 20px;
}

</style>
